import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { User, PaginatedResponse } from '../../types';

// 用户状态接口
interface UserState {
  users: User[];
  currentUser: User | null;
  total: number;
  loading: boolean;
  error: string | null;
  searchKeyword: string;
  filters: {
    role?: string;
    status?: string;
    shopId?: string;
  };
  pagination: {
    page: number;
    limit: number;
  };
}

// 初始状态
const initialState: UserState = {
  users: [],
  currentUser: null,
  total: 0,
  loading: false,
  error: null,
  searchKeyword: '',
  filters: {},
  pagination: {
    page: 1,
    limit: 20,
  },
};

// 异步actions
export const fetchUsers = createAsyncThunk(
  'user/fetchUsers',
  async (params: any, { rejectWithValue }) => {
    try {
      // 这里应该调用实际的API
      // const response = await UserService.getUsers(params);
      // return response;
      return { data: [], total: 0 } as PaginatedResponse<User>;
    } catch (error: any) {
      return rejectWithValue(error.message || '获取用户列表失败');
    }
  }
);

// 创建slice
const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setSearchKeyword: (state, action) => {
      state.searchKeyword = action.payload;
    },
    setFilters: (state, action) => {
      state.filters = { ...state.filters, ...action.payload };
    },
    setPagination: (state, action) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
    clearError: (state) => {
      state.error = null;
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchUsers.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchUsers.fulfilled, (state, action) => {
        state.loading = false;
        state.users = action.payload.data;
        state.total = action.payload.total;
      })
      .addCase(fetchUsers.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload as string;
      });
  },
});

export const { setSearchKeyword, setFilters, setPagination, clearError } = userSlice.actions;
export default userSlice.reducer;
